<template>
  <div class="rental-management">
    <div class="page-header">
      <h2 class="page-title">衣物租赁管理</h2>
    </div>

    <!-- 筛选区域 -->
    <el-card class="filter-card" shadow="always">
      <el-form :inline="true" :model="filterForm" class="filter-form" @submit.prevent>
        <el-form-item label="名称">
          <el-input
              v-model="filterForm.name"
              placeholder="请输入衣物名称"
              clearable
              @keyup.enter="fetchRentals"
              style="width: 200px"
          >
            <template #append>
              <el-button icon="el-icon-search" @click="fetchRentals" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
              v-model="filterForm.status"
              placeholder="全部状态"
              clearable
              @change="fetchRentals"
              style="width: 180px"
          >
            <el-option label="上架中" :value="2" />
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 衣物列表 -->
    <el-table
        :data="rentals"
        style="width: 100%"
        border
        v-loading="loading"
        class="custom-table"
        :default-sort="{ prop: 'rentalId', order: 'descending' }"
    >
      <el-table-column prop="rentalId" label="衣物ID" width="80" sortable align="center" />
      <el-table-column label="名称" min-width="180">
        <template #default="scope">
          {{ getRentalName(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column prop="pricePerHour" label="价格/小时" width="100" align="center" />
      <el-table-column prop="quantity" label="库存" width="80" align="center" />
      <el-table-column prop="size" label="尺码" width="80" align="center" />
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)" effect="dark" size="small">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="图片" width="130" align="center">
        <template #default="scope">
          <el-image
              :src="scope.row.imageUrl"
              style="width: 80px; height: 80px"
              fit="cover"
              lazy
              class="rental-image"
              :preview-src-list="[scope.row.imageUrl]"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="260" align="center">
        <template #default="scope">
          <el-button
              v-if="scope.row.status === 2"
              type="success"
              size="small"
              @click="updateStatus(scope.row.rentalId, 1)"
              style="margin-right: 10px"
          >
            通过
          </el-button>
          <el-button
              v-if="scope.row.status === 2 || scope.row.status === 1"
              type="danger"
              size="small"
              @click="updateStatus(scope.row.rentalId, 0)"
              style="margin-right: 10px"
          >
            {{ scope.row.status === 2 ? '拒绝' : '下架' }}
          </el-button>
          <el-button
              v-if="scope.row.status === 0"
              type="success"
              size="small"
              @click="updateStatus(scope.row.rentalId, 1)"
              style="margin-right: 10px"
          >
            上架
          </el-button>
          <el-button
              type="primary"
              size="small"
              @click="openEditDialog(scope.row)"
              style="margin-right: 10px"
              icon="el-icon-edit"
          >
            编辑
          </el-button>
          <el-button
              type="danger"
              size="small"
              @click="deleteRental(scope.row.rentalId)"
              icon="el-icon-delete"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
      <template #empty>
        <span class="empty-text">暂无数据</span>
      </template>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          background
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </div>

    <!-- 编辑衣物对话框 -->
    <el-dialog
        v-model="editDialogVisible"
        title="编辑衣物"
        width="500px"
        custom-class="custom-dialog"
        :close-on-click-modal="false"
    >
      <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="100px"
          class="dialog-form"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="价格/小时" prop="pricePerHour">
          <el-input
              v-model.number="editForm.pricePerHour"
              type="number"
              placeholder="请输入价格"
              min="0"
          />
        </el-form-item>
        <el-form-item label="库存" prop="quantity">
          <el-input
              v-model.number="editForm.quantity"
              type="number"
              placeholder="请输入库存"
              min="0"
          />
        </el-form-item>
        <el-form-item label="尺码" prop="size">
          <el-input v-model="editForm.size" placeholder="请输入尺码" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="上架中" :value="2" />
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRental" icon="el-icon-check">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'AdminRentalManagement',
  data() {
    return {
      rentals: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      filterForm: {
        name: '', // 新增名称搜索字段
        status: null,
      },
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        pricePerHour: [
          { required: true, message: '请输入价格', trigger: 'blur' },
          { type: 'number', message: '价格必须为数字', trigger: 'blur' },
        ],
        quantity: [
          { required: true, message: '请输入库存', trigger: 'blur' },
          { type: 'number', message: '库存必须为数字', trigger: 'blur' },
        ],
        size: [{ required: true, message: '请输入尺码', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
      },
    };
  },
  computed: {
    adminInfo() {
      return this.$store.state.adminInfo || JSON.parse(sessionStorage.getItem('adminInfo')) || {
        username: '超级星',
        role: 'super',
      };
    },
    isCollapsed() {
      return this.$parent.isCollapsed;
    },
  },
  watch: {
    isCollapsed() {
      this.$nextTick(() => {
        this.adjustLayout();
      });
    },
  },
  mounted() {
    this.fetchRentals();
    this.$nextTick(() => {
      this.adjustLayout();
    });
  },
  methods: {
    // 调整布局以适配侧边栏状态
    adjustLayout() {
      const content = this.$el.querySelector('.rental-management');
      if (content) {
        content.style.width = this.isCollapsed ? 'calc(100% - 60px)' : 'calc(100% - 220px)';
      }
    },
    // 获取衣物列表
    async fetchRentals() {
      try {
        this.loading = true;
        const token = sessionStorage.getItem('token');
        if (!token) {
          this.$message.error({ message: '未登录，请先登录', center: true });
          this.$router.push('/');
          return;
        }

        const role = this.adminInfo.role;
        const username = encodeURIComponent(this.adminInfo.username);

        const response = await axios.get(axios.defaults.baseURL+'/api/rentals/admin', {
          params: {
            page: this.currentPage,
            size: this.pageSize,
            name: this.filterForm.name || undefined, // 添加名称过滤参数
            status: this.filterForm.status,
          },
          headers: {
            Authorization: `Bearer ${token}`,
            Role: role,
            Username: username,
          },
        });

        this.rentals = response.data.data || [];
        this.total = response.data.total || 0;
        if (this.rentals.length === 0 && this.total > 0) {
          this.$message.warning({ message: '当前页无记录，请检查筛选条件', center: true });
        }
      } catch (error) {
        this.$message.error({
          message: '获取衣物列表失败: ' + (error.response?.data?.message || error.message),
          center: true,
        });
      } finally {
        this.loading = false;
      }
    },
    // 更新衣物状态
    async updateStatus(rentalId, status) {
      this.$confirm(
          `确定要${status === 1 ? '通过上架' : '拒绝/下架'}此衣物吗？`,
          '提示',
          { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
      )
          .then(async () => {
            try {
              const token = sessionStorage.getItem('token');
              const role = this.adminInfo.role;
              const username = encodeURIComponent(this.adminInfo.username);

              const response = await axios.post(
                  axios.defaults.baseURL+'/api/rentals/admin/updateStatus',
                  { rentalId, status },
                  {
                    headers: {
                      Authorization: `Bearer ${token}`,
                      Role: role,
                      Username: username,
                    },
                  }
              );

              if (response.data.success) {
                this.$message.success({ message: '状态更新成功', center: true });
                this.fetchRentals();
              } else {
                throw new Error(response.data.message || '状态更新失败');
              }
            } catch (error) {
              this.$message.error({
                message:
                    '状态更新失败: ' + (error.response?.data?.message || error.message),
                center: true,
              });
            }
          })
          .catch(() => {
            this.$message.info({ message: '操作已取消', center: true });
          });
    },
    // 保存编辑后的衣物
    async saveRental() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;

        try {
          const token = sessionStorage.getItem('token');
          const role = this.adminInfo.role;
          const username = encodeURIComponent(this.adminInfo.username);

          const rental = {
            rentalId: this.editForm.rentalId,
            setName: this.editForm.type === 'setName' ? this.editForm.name : null,
            topName: this.editForm.type === 'topName' ? this.editForm.name : null,
            pantsName: this.editForm.type === 'pantsName' ? this.editForm.name : null,
            skirtName: this.editForm.type === 'skirtName' ? this.editForm.name : null,
            shoesName: this.editForm.type === 'shoesName' ? this.editForm.name : null,
            accessoryName:
                this.editForm.type === 'accessoryName' ? this.editForm.name : null,
            pricePerHour: this.editForm.pricePerHour,
            quantity: this.editForm.quantity,
            size: this.editForm.size,
            status: this.editForm.status,
            merchantId: this.editForm.merchantId,
            imageUrl: this.editForm.imageUrl,
          };

          const response = await axios.put(
              axios.defaults.baseURL+'/api/rentals/admin/update',
              rental,
              {
                headers: {
                  Authorization: `Bearer ${token}`,
                  Role: role,
                  Username: username,
                },
              }
          );

          if (response.data.success) {
            this.$message.success({ message: '衣物更新成功', center: true });
            this.editDialogVisible = false;
            this.fetchRentals();
          } else {
            throw new Error(response.data.message || '更新失败');
          }
        } catch (error) {
          this.$message.error({
            message:
                '衣物更新失败: ' + (error.response?.data?.message || error.message),
            center: true,
          });
        }
      });
    },
    // 删除衣物
    async deleteRental(rentalId) {
      this.$confirm('确定要删除此衣物吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(async () => {
            try {
              const token = sessionStorage.getItem('token');
              const role = this.adminInfo.role;
              const username = encodeURIComponent(this.adminInfo.username);

              const response = await axios.delete(
                  axios.defaults.baseURL+`/api/rentals/admin/${rentalId}`,
                  {
                    headers: {
                      Authorization: `Bearer ${token}`,
                      Role: role,
                      Username: username,
                    },
                  }
              );

              if (response.data.success) {
                this.$message.success({ message: '衣物删除成功', center: true });
                this.fetchRentals();
              } else {
                throw new Error(response.data.message || '删除失败');
              }
            } catch (error) {
              this.$message.error({
                message:
                    '衣物删除失败: ' + (error.response?.data?.message || error.message),
                center: true,
              });
            }
          })
          .catch(() => {
            this.$message.info({ message: '删除已取消', center: true });
          });
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.fetchRentals();
    },
    handlePageChange(page) {
      this.currentPage = page;
      this.fetchRentals();
    },
    openEditDialog(rental) {
      const type = rental.setName
          ? 'setName'
          : rental.topName
              ? 'topName'
              : rental.pantsName
                  ? 'pantsName'
                  : rental.skirtName
                      ? 'skirtName'
                      : rental.shoesName
                          ? 'shoesName'
                          : 'accessoryName';
      this.editForm = {
        rentalId: rental.rentalId,
        name:
            rental.setName ||
            rental.topName ||
            rental.pantsName ||
            rental.skirtName ||
            rental.shoesName ||
            rental.accessoryName,
        pricePerHour: rental.pricePerHour,
        quantity: rental.quantity,
        size: rental.size,
        status: rental.status,
        merchantId: rental.merchantId,
        imageUrl: rental.imageUrl,
        type: type,
      };
      this.editDialogVisible = true;
    },
    getRentalName(rental) {
      return (
          rental.setName ||
          rental.topName ||
          rental.pantsName ||
          rental.skirtName ||
          rental.shoesName ||
          rental.accessoryName
      );
    },
    getStatusText(status) {
      return { 2: '上架中', 1: '上架', 0: '下架' }[status] || '未知';
    },
    getStatusTagType(status) {
      return { 2: 'warning', 1: 'success', 0: 'danger' }[status] || '';
    },
  },
};
</script>

<style scoped>
.rental-management {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 96px);
  width: 100%;
  transition: width 0.3s ease;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.filter-card {
  margin-bottom: 24px;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.filter-form {
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 20px;
}

.filter-form .el-form-item {
  margin-bottom: 0;
}

.custom-table {
  border-radius: 8px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.custom-table :deep(.el-table__header-wrapper th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

.custom-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

.rental-image {
  border-radius: 4px;
  transition: transform 0.3s;
  cursor: pointer;
}

.rental-image:hover {
  transform: scale(1.05);
}

.empty-text {
  color: #909399;
  font-size: 14px;
}

.pagination-container {
  padding: 20px 0;
  display: flex;
  justify-content: flex-end;
}

.custom-dialog {
  border-radius: 8px;
}

.dialog-form {
  padding: 0 20px;
}

.el-button {
  border-radius: 6px;
  transition: all 0.3s;
}

.el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.el-button[type="primary"] {
  background: #409eff;
  border-color: #409eff;
}

.el-button[type="success"] {
  background: #67c23a;
  border-color: #67c23a;
}

.el-button[type="danger"] {
  background: #f56c6c;
  border-color: #f56c6c;
}

.el-form-item {
  margin-bottom: 20px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 15px;
  font-weight: 600;
  color: #303133;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #f0f0f0;
  padding-top: 15px;
}

:deep(.el-input__inner) {
  border-radius: 6px;
}

:deep(.el-select .el-input__inner) {
  border-radius: 6px;
}
</style>